// MerchantServiceImpl.java
package cn.tedu.apps_system.service.impl;

import cn.tedu.apps_system.base.response.ResultCode;
import cn.tedu.apps_system.exception.BusinessException;
import cn.tedu.apps_system.mapper.MerchantMapper;
import cn.tedu.apps_system.pojo.dto.MerchantAddDTO;
import cn.tedu.apps_system.pojo.dto.MerchantUpdateDTO;
import cn.tedu.apps_system.pojo.entity.Merchant;
import cn.tedu.apps_system.pojo.vo.MerchantVO;
import cn.tedu.apps_system.service.MerchantService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

@Service
public class MerchantServiceImpl implements MerchantService {

    @Autowired
    private MerchantMapper merchantMapper;

    @Override
    public void add(MerchantAddDTO merchantAddDTO) {
        // 检查用户是否已经注册过商家
        Merchant existingMerchant = merchantMapper.selectByUserId(merchantAddDTO.getUserId());
        if (existingMerchant != null) {
            throw new BusinessException(ResultCode.MERCHANT_ALREADY_EXISTS);
        }

        Merchant merchant = new Merchant();
        BeanUtils.copyProperties(merchantAddDTO, merchant);
        merchant.setStatus(0); // 待审核状态
        merchant.setCreateTime(new Date());
        merchant.setUpdateTime(new Date());

        merchantMapper.insert(merchant);
    }

    @Override
    public void update(MerchantUpdateDTO merchantUpdateDTO) {
        Merchant merchant = merchantMapper.selectById(merchantUpdateDTO.getId());
        if (merchant == null) {
            throw new BusinessException(ResultCode.MERCHANT_NOT_EXIST);
        }

        BeanUtils.copyProperties(merchantUpdateDTO, merchant);
        merchant.setUpdateTime(new Date());

        merchantMapper.update(merchant);
    }

    @Override
    public void delete(Long id) {
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException(ResultCode.MERCHANT_NOT_EXIST);
        }

        merchantMapper.deleteById(id);
    }

    @Override
    public MerchantVO getById(Long id) {
        Merchant merchant = merchantMapper.selectById(id);
        if (merchant == null) {
            throw new BusinessException(ResultCode.MERCHANT_NOT_EXIST);
        }

        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        return merchantVO;
    }

    @Override
    public MerchantVO getByUserId(Long userId) {
        Merchant merchant = merchantMapper.selectByUserId(userId);
        if (merchant == null) {
            throw new BusinessException(ResultCode.MERCHANT_NOT_EXIST);
        }

        MerchantVO merchantVO = new MerchantVO();
        BeanUtils.copyProperties(merchant, merchantVO);
        return merchantVO;
    }
}